package com.shekhar.paas.story;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.shekhar.paas.domain.Story;

@Component
public class SimilarStoryFinder {

    @Autowired
    private MongoTemplate mongoTemplate;

    public Story associateSimilarStoriesTogether(Story story) {
        String[] tags = story.getTags();
        Date twoDaysBack = getStartDate();
        List<Story> stories = mongoTemplate.find(Query.query(Criteria.where("tags").in(tags).and("creationDate").gte(twoDaysBack)), Story.class);
        for (Story persistedStory : stories) {
            float jaccardSimilarityScore = new JaccardSimilarityScorer().score(story, persistedStory);
            if (jaccardSimilarityScore >= 0.2f) {
                float similarityScore = new LevenshteinSimilarityScorer().score(story, persistedStory);
                if (similarityScore >= 0.8f) {
                    String[] similarStories = persistedStory.getSimilarStories();
                    similarStories = ArrayUtils.add(similarStories, story.getId());
                    persistedStory.setSimilarStories(similarStories);
                    mongoTemplate.save(persistedStory);
                    story.setSimilarStories(ArrayUtils.add(story.getSimilarStories(), persistedStory.getId()));
                }
            }
        }
        return story;
    }

    private Date getStartDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 2);
        return calendar.getTime();
    }
}
